﻿package fab.buttons
{	
	import flash.display.DisplayObject;
	import flash.display.DisplayObjectContainer;
	import flash.display.MovieClip;
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.geom.Point;

	public class Tip extends Sprite
	{
		//private var gfx:MovieClip;
		private var gfx:Sprite;
		private var container:DisplayObjectContainer;
		private var targetPoint:Point;
		private var target:DisplayObject;
		private var relativeDecalage:Point = new Point();
		
		public function Tip( gfxClass:Class, target:DisplayObject, container:DisplayObjectContainer, texte:String="", _relativeDecalage:Point=null )
		{
			this.target = target;
			this.container = container;
			if ( _relativeDecalage ) this.relativeDecalage = _relativeDecalage;
			mouseEnabled = false;
			mouseChildren = false;
			gfx = new gfxClass();
			//gfx.gotoAndStop( 1 );
			//gfx.addFrameScript( gfx.totalFrames - 1, gfx.stop );
			addChild( gfx );
			if ( texte != "" ) gfx["texte"].htmlText = texte;
			buttonMode = true;
			target.addEventListener(MouseEvent.MOUSE_OVER, survole );
			target.addEventListener(MouseEvent.MOUSE_OUT, sort );
			target.addEventListener(MouseEvent.CLICK, click );
			
			targetPoint = container.globalToLocal( target.localToGlobal(new Point()) );
			gfx.x = targetPoint.x + relativeDecalage.x;
			gfx.y = targetPoint.y + relativeDecalage.y;
			
		}
		
		private function click(e:MouseEvent):void 
		{
			sort();
		}
		static public function add(gfxClass:Class, target:DisplayObject, container:DisplayObjectContainer, texte:String="", relativeDecalage:Point=null):void
		{
			new Tip( gfxClass, target, container, texte, relativeDecalage );
		}
		private function showCondition():Boolean
		{
			var pt:Point = container.globalToLocal( target.localToGlobal(new Point()) );
			return Point.distance( targetPoint, pt ) < 5;
		}
		private function survole(event:MouseEvent):void
		{
			if ( !showCondition() ) return sort();
			//gfx.gotoAndPlay( 1 );
			container.addChild( this );
		}
		private function sort(event:MouseEvent=null):void
		{
			//gfx.gotoAndStop( 1 );
			if ( container.contains( this ) ) container.removeChild( this );
		}
	}
}